<template>
	<view class="wrap">
    <loading-sync :isShow="isShowLoading" :isShowPercent="false" :complete="complete" :total="total" :title="loadingTitle"></loading-sync>
	</view>
</template>

<script>
import LoadingSync from '@/components/loading/loading-sync.vue'
import ds from '@/api/service/db-service.js'
import storeSer from '@/api/service/store-service.js'
import { checkPermi } from '@/utils/permission.js'

export default {
  components: {
    LoadingSync
  },
	data() {
		return {
      isShowLoading: false,
      complete: 0,
      total: 0,
			loadingTitle: null
		}
	},
	onLoad () {
		this.initView()
	},
	methods: {
    async initView () {
      let user = this.getCurrentUser() || {}
      let params = {
        userId: user.userId
      }
			// 存储的系统配置
			let sc = await storeSer.getSystemConfig()
			// 配置信息
			let remember = this.$store.state.vuex_remember
			let count = remember[user.userId]
			// 权限检测
			let checkPer = this.checkApiPerm
			/* 未初始化 */
			if (!sc.length) {
				// 初始化本地数据
				this.updateConfig(checkPer)
			}
			/* 已初始化 */
			else {
				let curParam = this.getParams()
				// 个人中心点击更新
				if (String(curParam.type) === '2') {
					this.updateConfig(checkPer)
				}
				// 登录后自动更新
				else {
					this.updateConfig(function(item){
						let b = checkPer(item)
						// 非首次登录时只更新待检清单
						if (count > 1) {
							// 待检清单
							b = /waitlist/i.test(item.tableName) && b
						}
						return b
					})
				}
			}
		},
		// 更新配置数据
		updateConfig (check) {
			this.isShowLoading = true
			ds.initSqlData(this, (item) => {
				this.loadingTitle = '加载：' + item.name
			}, check).then(() => {
				this.loadingTitle = '加载：' + '系统配置'
				// 初始化本地缓存
				return storeSer.initStorageData()
			}).then((res) => {
				if (res !== false) {
					this.isShowLoading = false
					navigateOnUpdate({ vm: this })
				}
			})
		},
		// 地址与权限检测
		checkApiPerm (item) {
			// 权限与接口对应地址
			let map = {
				'bridge:routineInspection:push': '/bridge/routineInspection',
				'culvert:constantlyInspection:push': '/culvert/constantlyInspection',
				'tunnel:routineExamination:push': '/tunnel/routineExamination'
			}
			let b = true
			for (let key in map) {
				let path = map[key]
				if (String(item.url).indexOf(path) > -1) {
					b = checkPermi([key])
				}
			}
			return b
		}
	}
};

// 升级页面导航
export const navigateOnUpdate = function ({ vm }) {
	let route = vm.getRoute()
	if (/user\/update/.test(route)) {
		let curParam = vm.getParams() || {}
		// 跳转至个人中心
		if (String(curParam.type) === '2') {
			uni.reLaunch({
				url: '/pages/sys/user/index'
			})
		}
		// 跳转至工作台
		else {
			uni.reLaunch({
				url: '/pages/sys/workbench/index?source=update'
			})
		}
	}
}
</script>
<style lang="scss">
@import 'index.scss';
page {
	background-color: #f5f5f5;
}
</style>
